package com.kcl.dfss.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.libvlc.util.VLCInstance;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.kcl.dfss.LocationService;
import com.kcl.dfss.LoginActivity;
import com.kcl.dfss.R;
import com.kcl.dfss.RegisterActivity;

public class AppUtils {
	private static final String tag = "AppUtils";

	public boolean getAppIsFirstRun() {
		return true;
	}

	public static LibVLC getLibVlcInstance(Context context) throws LibVlcException {
		Log.d("Kyle","getLibVlcInstance");
		LibVLC instance = LibVLC.getExistingInstance();
		if (instance == null) {
			Log.d("Kyle", "vlc instance is null, create a new one");

			instance = VLCInstance.getLibVlcInstance(context);
			
			SharedPreferences pref = PreferenceManager
					.getDefaultSharedPreferences(context);
			updateLibVlcSettings(pref);
			instance.init(context);
		}
		return instance;
	}

	
	public static void updateLibVlcSettings(SharedPreferences pref) {
		LibVLC instance = LibVLC.getExistingInstance();
		if (instance == null)
			return;

		instance.setSubtitlesEncoding(pref.getString("subtitles_text_encoding",
				""));
		instance.setTimeStretching(pref.getBoolean(
				"enable_time_stretching_audio", false));
		instance.setFrameSkip(pref.getBoolean("enable_frame_skip", false));
		instance.setChroma(pref.getString("chroma_format", ""));
		instance.setVerboseMode(pref.getBoolean("enable_verbose_mode", true));

		if (pref.getBoolean("equalizer_enabled", false))
			instance.setEqualizer(getFloatArray(pref, "equalizer_values"));

		int aout;
		try {
			aout = Integer.parseInt(pref.getString("aout", "-1"));
		} catch (NumberFormatException nfe) {
			aout = -1;
		}
		int vout;
		try {
			vout = Integer.parseInt(pref.getString("vout", "-1"));
		} catch (NumberFormatException nfe) {
			vout = -1;
		}
		int deblocking;
		try {
			deblocking = Integer.parseInt(pref.getString("deblocking", "-1"));
		} catch (NumberFormatException nfe) {
			deblocking = -1;
		}
		int networkCaching = pref.getInt("network_caching_value", 0);
		if (networkCaching > 60000)
			networkCaching = 60000;
		else if (networkCaching < 0)
			networkCaching = 0;
		instance.setAout(aout);
		instance.setVout(vout);
		instance.setDeblocking(deblocking);
		instance.setNetworkCaching(networkCaching);
	}

	public static float[] getFloatArray(SharedPreferences pref, String key) {
		float[] array = null;
		String s = pref.getString(key, null);
		if (s != null) {
			try {
				JSONArray json = new JSONArray(s);
				array = new float[json.length()];
				for (int i = 0; i < array.length; i++)
					array[i] = (float) json.getDouble(i);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return array;
	}
	public static String __FUNC__(){
		StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
		return traceElement.getMethodName() + "\n";
	}
	
	//判断网络连接是否可用
	public static boolean isNetworkAvailable(Context context){
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(cm == null){
		}else{
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if(info != null){
				for(int i=0;i<info.length;i++){
					if(info[i].getState() == NetworkInfo.State.CONNECTED){
						return true;
					}
				}
			}
		}
		return false;
	}
	
	//提醒登录或注册对话框
	public static void showdialog(final Context context){
		final AlertDialog dig = new AlertDialog.Builder(context).create();
//		dig.setCancelable(false);
		dig.setCanceledOnTouchOutside(false);
		dig.show();
		Window window = dig.getWindow();
		window.setContentView(R.layout.dialog);
		Button btn_reg = (Button) window.findViewById(R.id.dia_register);
		Button btn_log = (Button) window.findViewById(R.id.dia_login);
		btn_reg.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(context, RegisterActivity.class);
				context.startActivity(intent);
				dig.dismiss();
			}
		});
		btn_log.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(context, LoginActivity.class);
				context.startActivity(intent);
				dig.dismiss();
			}
		});
	}
	
	
	//计算listview高度
	public static void setListViewHeight(ListView listview){
		ListAdapter listAdapter = listview.getAdapter();
		if(listAdapter == null){
			return;
		}
		int totalHeight = 0;
		for(int i=0,len = listAdapter.getCount();i<len;i++){
			View listItem = listAdapter.getView(i, null, listview);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		
		ViewGroup.LayoutParams params = listview.getLayoutParams();
		params.height = totalHeight + (listview.getDividerHeight()*(listAdapter.getCount()-1));
		
		listview.setLayoutParams(params);
	}
	
	//device立即成效对话框
	public static void showDialog(final Activity context,String message){
		Dialog dialog = new AlertDialog.Builder(context)
        .setTitle("系统提示") 
        .setMessage(message) 
        .setNeutralButton("确定", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dialog.dismiss();
                }
            })
        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        }).create();
    dialog.show(); 
	}
	
	public static Bitmap getHttpBitmap(String url){
		URL myUrl;
		Bitmap bitmap = null;
		try {
			myUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
			conn.setConnectTimeout(10000);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	//正则表达式验证输入的是否是11位数字
	public static boolean stringFileter(String str){
		boolean b = false;
		String regEx = "[0-9]{11}";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		b = m.matches();
		return b;
	}
	
	//判断GPS是否打开
	public static boolean getGPSState(Context context){
		/*String str = Settings.Secure.getString(context.getContentResolver(),  
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
		Log.i(tag, "GPS状态："+str);
		if(str != null){
			return str.contains("gps");
		}else{
			return false;
		}*/
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		Log.i(tag, "GPS状态："+gps);
		if(gps){
			return true;
		}
		return false;
	}
	
	//打开或关闭GPS
	public static void toggleGPS(Context context){
		/*Intent gpsIntent = new Intent();
		gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
		gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
		gpsIntent.setData(Uri.parse("custom:3"));
		try {
			PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
			Log.i(tag, "执行到toggleGPS方法");
		} catch (CanceledException e) {
			e.printStackTrace();
		}*/
		final Intent poke = new Intent();
	    poke.setClassName("com.android.settings", 
	        "com.android.settings.widget.SettingsAppWidgetProvider");
	    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
	    poke.setData(Uri.parse("3"));
	    context.sendBroadcast(poke);
	}
	
	public static void showGPSDialog(final Activity context){
		Dialog dialog = new AlertDialog.Builder(context)
        .setTitle("系统提示") 
        .setMessage("测速需打开GPS") 
        .setNeutralButton("不再提示", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	SharedPreferences preferences = context.getSharedPreferences("shared_login", 0);
                	preferences.edit().putBoolean("gps_remind", false).commit();
                	dialog.dismiss();
                }
            })
        .setPositiveButton("去打开", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            	context.startActivity(intent);
                dialog.dismiss();
            }
        }).create();
    dialog.show(); 
	}
	
}
